package com.dream.technology.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

import static net.logstash.logback.argument.StructuredArguments.keyValue;


/**
 * @author chenqi1@feihe.com
 * @version 1.0
 * @date 2020/12/3 1:50 下午
 */
@Slf4j

public class TraceIdInterceptor implements HandlerInterceptor {


    public static final String REQUEST_START = "req_start";
    public static final String REQUEST_end = "req_end";
    public static final String TRACE_ID = "trace_id";
    public static final String EXECUTE_TIME = "execute_time";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = UUID.randomUUID().toString().toUpperCase();

        MDC.put("trace_id", traceId);
        request.setAttribute(REQUEST_START, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {

        long start = (Long) request.getAttribute(REQUEST_START);
        log.info("complete",keyValue("exeTm",String.valueOf(System.currentTimeMillis()-start)));
        if (ex !=null){
            log.info(ex.getMessage(),keyValue("exeTm",String.valueOf(System.currentTimeMillis()-start)));
        }

        // 清除mdc标示
        MDC.clear();

    }


}
